﻿using AnlianCommon.Common.Domains.ProductionManagement;
using AnlianCommon.Common.DTO;
using AnlianCommon.Common.Infrastructure.IRepository;
using AnlianCommon.Enum;
using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace SheepCommon.API.SheepCommands.EwesGiveBirthes
{
    public class EwesGiveBirthCreateHandler : IRequestHandler<EwesGiveBirthCreateCommand, Result>
    {
        private readonly IBaseRepository<EwesGiveBirth> _ewesGiveBirthRepository;
        private readonly IBaseRepository<SheepArchives> _archivesRepository;
        private readonly IMapper _mapper;

        public EwesGiveBirthCreateHandler(IBaseRepository<EwesGiveBirth> ewesGiveBirthRepository, IBaseRepository<SheepArchives> archivesRepository, IMapper mapper)
        {
            _ewesGiveBirthRepository = ewesGiveBirthRepository;
            _archivesRepository = archivesRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(EwesGiveBirthCreateCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                EwesGiveBirth ewesGiveBirth = _mapper.Map<EwesGiveBirth>(request);
                ewesGiveBirth.CreatedOwnerId = "张三";
                ewesGiveBirth.CreatedTime = DateTime.Now;
                var res = await _ewesGiveBirthRepository.Add(ewesGiveBirth);
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "添加成功";
                    var sheep = await (await _archivesRepository.GetAll()).Where(c => c.RecordAuricle == ewesGiveBirth.EarBugles).FirstOrDefaultAsync();
                    if (sheep != null)
                    {
                        sheep.ReproductiveState = 8;//1表示后备空怀,2返情空怀,3未孕空怀,4流产空怀,5空胎空怀,6断奶空怀,7妊检,8哺乳
                        var sheepArchives = await _archivesRepository.Update(sheep);
                    }
                }
                else
                {
                    result.Code = (int)CommonErrorCode.Added;
                    result.Msg = "添加失败";
                }
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
    }
}
